---
import ItemContent from "@components/style/ItemContent.astro";
---

<section th:with="createUser=${article.createUser}">
  <ItemContent>
    <div class="w-full flex justify-center item-center">
      <div class="flex flex-col items-center pt-4">
        <img
          class="w-24 h-24 mb-3 rounded-full shadow-lg"
          th:src="${imgPrefix+createUser.avatar}"
          th:alt="${createUser.nickName}"
        />
        <span
          class="mb-1 text-xl font-medium text-gray-900 dark:text-white"
          th:text="${createUser.nickName}"
        >
          张三
        </span>
        <span
          class="text-sm text-gray-500 dark:text-gray-400"
          th:text="${createUser.remark}">痛苦并快乐着</span
        >
        <div class="flex mt-2">
          <span
            th:text="${#strings.isEmpty(article.reprintUrl)?'原创':'转载'}"
            class="inline-flex items-center px-4 py-2 text-sm font-medium text-center text-white bg-blue-900 rounded-lg hover:bg-blue-800 focus:ring-4 focus:outline-none focus:ring-blue-300 dark:bg-blue-600 dark:hover:bg-blue-700 dark:focus:ring-blue-800"
            >原创</span
          >
          <a
            th:href="${#strings.isEmpty(article.reprintUrl)?(webConfig['oly.web.domain']+'/article/'+article.articleId):article.reprintUrl}"
            th:text="${#strings.isEmpty(article.reprintUrl)?article.articleTitle:(('本文转载地址为:'+article.reprintUrl))}"
            class="max-w-60 py-2 text-ellipsis text-nowrap overflow-hidden px-4 ms-2 text-sm font-medium text-gray-900 focus:outline-none bg-white rounded-lg border border-gray-200 hover:bg-gray-100 hover:text-blue-700 focus:z-10 focus:ring-4 focus:ring-gray-100 dark:focus:ring-gray-700 dark:bg-gray-800 dark:text-gray-400 dark:border-gray-600 dark:hover:text-white dark:hover:bg-gray-700"
            >Message原创原创原fgddddddddddddddddddddd创原创原创</a
          >
        </div>
        <div class="flex mt-4">
          <button
            id="likeButton"
            type="button"
            class="relative m-1 p-2 rounded-full cursor-pointer text-gray-800 dark:text-white  transition-colors"
            title="点赞"
          >
            <svg
              xmlns="http://www.w3.org/2000/svg"
              fill="none"
              viewBox="0 0 24 24"
              stroke-width="1.5"
              stroke="currentColor"
              class="w-6 h-6 "
            >
              <path
                stroke-linecap="round"
                stroke-linejoin="round"
                d="M6.633 10.25c.806 0 1.533-.446 2.031-1.08a9.041 9.041 0 0 1 2.861-2.4c.723-.384 1.35-.956 1.653-1.715a4.498 4.498 0 0 0 .322-1.672V2.75a.75.75 0 0 1 .75-.75 2.25 2.25 0 0 1 2.25 2.25c0 1.152-.26 2.243-.723 3.218-.266.558.107 1.282.725 1.282m0 0h3.126c1.026 0 1.945.694 2.054 1.715.045.422.068.85.068 1.285a11.95 11.95 0 0 1-2.649 7.521c-.388.482-.987.729-1.605.729H13.48c-.483 0-.964-.078-1.423-.23l-3.114-1.04a4.501 4.501 0 0 0-1.423-.23H5.904m10.598-9.75H14.25M5.904 18.5c.083.205.173.405.27.602.197.4-.078.898-.523.898h-.908c-.889 0-1.713-.518-1.972-1.368a12 12 0 0 1-.521-3.507c0-1.553.295-3.036.831-4.398C3.387 9.953 4.167 9.5 5 9.5h1.053c.472 0 .745.556.5.96a8.958 8.958 0 0 0-1.302 4.665c0 1.194.232 2.333.654 3.375Z"
              ></path>
            </svg>
            <span class="sr-only">点赞</span>
            <div
              class="absolute inline-flex items-center justify-center w-6 h-6 text-xs font-bold text-white bg-red-500 border-2 border-white rounded-full -top-2 -end-2 dark:border-gray-900"
            >
              <span
                id="likeCount"
                th:text="${article?.articleCount?.recordLike>0?article?.articleCount?.recordLike:'0'}">0</span>
            </div>
          </button>
          <th:block
            th:if="${webConfig['oly.web.theme.nice.reward.open']=='true'}"
          >
            <button
              type="button"
              id="rewardDropButton"
              data-dropdown-toggle="rewardDrop"
              data-dropdown-placement="top"
              class="m-1 p-2 rounded-full cursor-pointer transition-colors"
              title="赞赏"
            >
             <span class="text-4xl text-gray-800 dark:text-white">赏</span>
            </button>
            <!-- Dropdown menu -->
            <div
              id="rewardDrop"
              class="z-20 hidden w-72 bg-white overflow-hidden rounded-lg border border-gray-200/10 dark:text-white dark:bg-neutral-900 dark:border-gray-700"
              aria-labelledby="rewardDropButton"
            >
              <div
                class="divide-y divide-gray-100 dark:divide-gray-700 w-72 p-2"
                th:with="weiPlay=${webConfig['oly.web.theme.nice.reward.wei']},zhiPlay=${webConfig['oly.web.theme.nice.reward.zhi']}"
              >
                <div class="grid grid-cols-6 gap-4">
                  <div
                    class="col-start-1 col-end-7 text-center"
                    th:utext="${#strings.isEmpty(webConfig['oly.web.theme.nice.reward.title'])?'你的支持是我前进的动力':webConfig['oly.web.theme.nice.reward.title']}"
                  >
                    你的支持是我前进的动力
                  </div>
                  <div class="col-start-1 col-end-4">
                    <img
                      class="rounded-lg border border-gray-200/10"
                      th:src="${#strings.isEmpty(weiPlay)?'/nice/static/images/pay/pay.png':(imgPrefix+weiPlay)}"
                      alt="微信支付"
                    />
                    <h2 class="text-center">微信</h2>
                  </div>
                  <div class="col-end-7 col-span-3">
                    <img
                      class="rounded-lg border border-gray-200/10"
                      th:src="${#strings.isEmpty(weiPlay)?'/nice/static/images/pay/pay.png':(imgPrefix+zhiPlay)}"
                      alt="支付宝支付"
                    />
                    <h2 class="text-center">支付宝</h2>
                  </div>
                  <div
                    class="col-start-1 col-end-7 text-center rounded-lg border border-gray-200/10"
                    th:utext="${#strings.isEmpty(webConfig['oly.web.theme.nice.reward.footer'])?'<h2>赞赏名单</h2>
              <p>你们的支持让我的文章有价值</p>':webConfig['oly.web.theme.nice.reward.footer']}"
                  >
                    <h2>赞赏名单</h2>
                    <p>你们的支持让我的文章有价值</p>
                  </div>
                </div>
              </div>
            </div>
          </th:block>
          <button
            type="button"
            id="dislikeButton"
            class="relative m-1 p-2 rounded-full cursor-pointer text-gray-800 dark:text-white  transition-colors"
            title="踩"
          >
            <svg
              xmlns="http://www.w3.org/2000/svg"
              fill="none"
              viewBox="0 0 24 24"
              stroke-width="1.5"
              stroke="currentColor"
              class="w-6 h-6 "
            >
              <path
                stroke-linecap="round"
                stroke-linejoin="round"
                d="M7.498 15.25H4.372c-1.026 0-1.945-.694-2.054-1.715a12.137 12.137 0 0 1-.068-1.285c0-2.848.992-5.464 2.649-7.521C5.287 4.247 5.886 4 6.504 4h4.016a4.5 4.5 0 0 1 1.423.23l3.114 1.04a4.5 4.5 0 0 0 1.423.23h1.294M7.498 15.25c.618 0 .991.724.725 1.282A7.471 7.471 0 0 0 7.5 19.75 2.25 2.25 0 0 0 9.75 22a.75.75 0 0 0 .75-.75v-.633c0-.573.11-1.14.322-1.672.304-.76.93-1.33 1.653-1.715a9.04 9.04 0 0 0 2.86-2.4c.498-.634 1.226-1.08 2.032-1.08h.384m-10.253 1.5H9.7m8.075-9.75c.01.05.027.1.05.148.593 1.2.925 2.55.925 3.977 0 1.487-.36 2.89-.999 4.125m.023-8.25c-.076-.365.183-.75.575-.75h.908c.889 0 1.713.518 1.972 1.368.339 1.11.521 2.287.521 3.507 0 1.553-.295 3.036-.831 4.398-.306.774-1.086 1.227-1.918 1.227h-1.053c-.472 0-.745-.556-.5-.96a8.95 8.95 0 0 0 .303-.54"
              ></path>
            </svg>
            <span class="sr-only">踩</span>
            <div
              class="absolute inline-flex items-center justify-center w-6 h-6 text-xs font-bold text-white bg-red-500 border-2 border-white rounded-full -top-2 -end-2 dark:border-gray-900"
            >
              <span
                id="dislikeCount"
                th:text="${article?.articleCount?.recordNasty>0?article?.articleCount?.recordNasty:'0'}">0</span>
            </div>
          </button>
        </div>
        <div
          class="flex items-center mt-4 p-4 mb-4 text-sm text-blue-800 rounded-lg bg-blue-50 dark:bg-gray-800 dark:text-blue-400"
          role="alert"
        >
          <div>
            <span class="font-medium">Info alert!</span
            >本博客所有文章除特别声明外，均采用 CC BY-NC-SA 4.0
            许可协议。转载请注明来自 Calyee`Blog！
          </div>
        </div>
      </div>
    </div>
    <div class="flex mt-4 justify-end mr-10 pb-5">
      <button
        type="button"
        class="m-1 p-2 rounded-full hover:bg-gray-200 dark:hover:bg-gray-700 transition-colors"
        title="分享到微博"
      >
        <svg
          class="w-5 h-5 text-gray-800 dark:text-white"
          aria-hidden="true"
          xmlns="http://www.w3.org/2000/svg"
          fill="currentColor"
          viewBox="0 0 18 18"
        >
          <path
            d="M3 7H1a1 1 0 0 0-1 1v8a2 2 0 0 0 4 0V8a1 1 0 0 0-1-1Zm12.954 0H12l1.558-4.5a1.778 1.778 0 0 0-3.331-1.06A24.859 24.859 0 0 1 6 6.8v9.586h.114C8.223 16.969 11.015 18 13.6 18c1.4 0 1.592-.526 1.88-1.317l2.354-7A2 2 0 0 0 15.954 7Z"
          ></path>
        </svg>
      </button>
      <button
        type="button"
        class="m-1 p-2 rounded-full hover:bg-gray-200 dark:hover:bg-gray-700 transition-colors"
        title="分享到微信"
      >
        <svg
          class="w-5 h-5 text-gray-800 dark:text-white"
          aria-hidden="true"
          xmlns="http://www.w3.org/2000/svg"
          fill="currentColor"
          viewBox="0 0 18 18"
        >
          <path
            d="M3 7H1a1 1 0 0 0-1 1v8a2 2 0 0 0 4 0V8a1 1 0 0 0-1-1Zm12.954 0H12l1.558-4.5a1.778 1.778 0 0 0-3.331-1.06A24.859 24.859 0 0 1 6 6.8v9.586h.114C8.223 16.969 11.015 18 13.6 18c1.4 0 1.592-.526 1.88-1.317l2.354-7A2 2 0 0 0 15.954 7Z"
          ></path>
        </svg>
      </button>

      <button
        type="button"
        class="m-1 p-2 rounded-full hover:bg-gray-200 dark:hover:bg-gray-700 transition-colors"
        title="分享到QQ"
      >
        <svg
          class="w-5 h-5 text-gray-800 dark:text-white"
          aria-hidden="true"
          xmlns="http://www.w3.org/2000/svg"
          fill="currentColor"
          viewBox="0 0 18 18"
        >
          <path
            d="M3 7H1a1 1 0 0 0-1 1v8a2 2 0 0 0 4 0V8a1 1 0 0 0-1-1Zm12.954 0H12l1.558-4.5a1.778 1.778 0 0 0-3.331-1.06A24.859 24.859 0 0 1 6 6.8v9.586h.114C8.223 16.969 11.015 18 13.6 18c1.4 0 1.592-.526 1.88-1.317l2.354-7A2 2 0 0 0 15.954 7Z"
          ></path>
        </svg>
      </button>
    </div>
  </ItemContent>
</section>
<script>
  import { fetchDataWithPost, fetchDataWithGet } from "@/utils/fatch.js";
    import { info, error, success } from '@components/common/toast/index.js';
    let isLiked = false;
  let isDisliked = false;
  let likeCount = 0;
  let dislikeCount = 0;

  // 获取页面元素
  const likeButton = document.getElementById("likeButton");
  const dislikeButton = document.getElementById("dislikeButton");
  const likeCountEl = document.getElementById("likeCount");
  const dislikeCountEl = document.getElementById("dislikeCount");
  const userName = document.getElementById("userName");
  const articleId = document.getElementById("articleId");
  const themeName = document.getElementById("themeName");

  // 兼容性检查：确保所有必要的 DOM 元素都存在
  if (!likeButton || !dislikeButton || !likeCountEl || !dislikeCountEl) {
    console.error("无法找到必要的 DOM 元素，点赞和点踩功能可能无法正常工作");
  } else {
    // 初始化计数，从DOM元素中获取实际值
    if (likeCountEl.textContent) {
      likeCount = parseInt(likeCountEl.textContent) || 0;
    }
    if (dislikeCountEl.textContent) {
      dislikeCount = parseInt(dislikeCountEl.textContent) || 0;
    }
  }

  // 更新 UI 状态
  function updateUI() {
    if (likeCountEl && dislikeCountEl) {
      likeCountEl.textContent = likeCount;
      dislikeCountEl.textContent = dislikeCount;
    }

    // 更新点赞按钮样式
    if (isLiked && likeButton) {
      likeButton.classList.add("text-blue-500");
      likeButton.classList.remove("text-gray-800", "dark:text-white");
    } else if (likeButton) {
      likeButton.classList.remove("text-blue-500");
      likeButton.classList.add("text-gray-800", "dark:text-white");
    }

    // 更新踩按钮样式
    if (isDisliked && dislikeButton) {
      dislikeButton.classList.add("text-red-600");
      dislikeButton.classList.remove("text-gray-800", "dark:text-white");
    } else if (dislikeButton) {
      dislikeButton.classList.remove("text-red-600");
      dislikeButton.classList.add("text-gray-800", "dark:text-white");
    }
  }

  // 添加浏览记录
  function addLook() {
    fetchDataWithPost(
      `/${themeName.value}/general/record/ARTICLE/addLookRecord`,
      { recordId: articleId.value },
    )
      .then((response) => {
        console.log("浏览记录添加成功:", response);
      })
      .catch((error) => {
        console.error("添加浏览记录失败:", error);
      });
  }

  // 点赞功能
  function addLike() {
    if (isLogin()) {
      fetchDataWithPost(
        `/${themeName.value}/hand/record/ARTICLE/addLikeRecord`,
        { recordId: articleId.value },
      )
        .then((response) => {
          console.log("点赞请求响应:", response);
          if (response && response.data) {
            // 根据后端返回的类型进行不同处理
            if (response.data === "nastied") {
              // 用户已经踩了，不能再喜欢
              showMessage("您已经踩了这篇文章，不能同时点赞", "warning");
            } else if (response.data === "cancel") {
              // 用户取消点赞
              isLiked = false;
              likeCount = response.data.likeCount || likeCount - 1;
              showMessage("已取消点赞", "info");
              updateUI();
            } else if (response.data === "update") {
              // 用户再次点赞
              isLiked = true;
              likeCount = response.data.likeCount || likeCount + 1;
              showMessage("点赞成功！", "success");
              updateUI();
            } else if (response.data === "add" || response.data.success) {
              // 用户点赞（向后兼容）
              isLiked = true;
              likeCount = response.data.likeCount || likeCount + 1;
              showMessage("点赞成功！", "success");
              updateUI();
            } else {
              // 其他失败情况
              showMessage("点赞失败，请重试", "error");
            }
          } else {
            showMessage("点赞失败，请重试", "error");
          }
        })
        .catch((error) => {
          console.error("点赞请求异常:", error);
          showMessage("网络错误，请重试", "error");
        });
    }
  }

  // 踩功能
  function addNasty() {
    if (isLogin()) {
      fetchDataWithPost(
        `/${themeName.value}/hand/record/ARTICLE/addNastyRecord`,
        { recordId: articleId.value },
      ).then((response) => {
        if (response && response.data) {
          // 根据后端返回的类型进行不同处理
          if (response.data === "liked") {
            // 用户已经点赞了，不能再踩
            showMessage("您已经点赞了这篇文章，不能同时踩", "warning");
          } else if (response.data === "cancel") {
            // 用户取消踩
            isDisliked = false;
            dislikeCount = response.data.dislikeCount || dislikeCount - 1;
            showMessage("已取消不喜欢", "info");
            updateUI();
          } else if (response.data === "update") {
            // 用户再次踩
            isDisliked = true;
            dislikeCount = response.data.dislikeCount || dislikeCount + 1;
            showMessage("已标记不喜欢", "success");
            updateUI();
          }
        }
      });
    }
  }

  function isLogin() {
    if (userName.value) {
      return true;
    }
    showMessage("请先登录", "error");
    return false;
  }

  // 显示提示消息
  function showMessage(message, type = "info") {
    // 使用我们的Toast组件便捷方法
    const duration = 3000; // 保持原有的3秒自动消失
    
    switch(type) {
      case "success":
        success(message, duration);
        break;
      case "error":
        error(message, duration);
        break;
      default:
        info(message, duration);
    }
  }

  // 检查用户是否已点赞或踩过
  function checkUserRecordStatus() {
    if (userName.value) {
      // 使用fetchDataWithGet获取用户记录状态
      fetchDataWithGet(
        `/${themeName.value}/api/record/getCmsRecordVo/article_${articleId.value}/${userName.value}`
      )
        .then((response) => {
          console.log("获取用户记录状态响应:", response);
          if (response && response.data) {
            // 根据返回结果设置点赞和踩状态
            // 如果likeRecord不为null，需要判断其visible属性是否为0
            isLiked = response.data.likeRecord && response.data.likeRecord.visible === 0;
            isDisliked = response.data.nastyRecord && response.data.nastyRecord.visible === 0;
            // 更新UI显示
            updateUI();
          }
        })
        .catch((error) => {
          console.error("获取用户记录状态失败:", error);
        });
    }
  }

  // 绑定事件监听
  if (likeButton && dislikeButton) {
    likeButton.addEventListener("click", addLike);
    dislikeButton.addEventListener("click", addNasty);

    // 添加浏览记录
    addLook();
    
    // 检查用户是否已点赞或踩过
    checkUserRecordStatus();
  }

  // 导出函数以便测试或其他组件使用
  export { addLike, addNasty };
</script>
